/* eslint-disable*/
import api from '@/apiHttp/http/index.js'
//中英文翻译  //在组件中需要更换字眼 就用 $lang['xxx']
export const translate = function () {
    let language = require(`@/assets/lang/zh.js`).lang
    let str = window.navigator.userAgent
    // console.warn("当前语言：：：：：",window.navigator.userAgent); 
    // console.warn("当前语言：：：：：",str + '',str.indexOf("en-CN")); 
    //判断当前环境语言是否为英文
    // console.warn("当前userAgent",str);
    if (str.indexOf("lang:en-") > -1) {
        language = require(`@/assets/lang/en.js`).lang
    }
    return language
}

const $lang = translate()


// 获取文件大小
export const getFileSize = (limit) => {
    var size = ''
    if (limit < 0.1 * 1024) {
        //如果小于0.1KB转化成B
        size = limit.toFixed(2) + 'B'
    } else if (limit < 0.1 * 1024 * 1024) {
        //如果小于0.1MB转化成KB
        size = (limit / 1024).toFixed(2) + 'KB'
    } else if (limit < 0.1 * 1024 * 1024 * 1024) {
        //如果小于0.1GB转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
    } else {
        //其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
    }

    var sizestr = size + ''
    var len = sizestr.indexOf('.')
    var dec = sizestr.substr(len + 1, 2)
    if (dec == '00') {
        //当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
    }
    return sizestr
}


// 文件转2进制
export const fileToBinary = (file, piece = 1024 * 1024 * 3) => {
    let totalSize = file.size; // 文件总大小
    let start = 0; // 每次上传的开始字节
    let end = start + piece; // 每次上传的结尾字节
    let chunks = []
    while (start < totalSize) {
        // 根据长度截取每次需要上传的数据
        // File对象继承自Blob对象，因此包含slice方法
        let blob = file.slice(start, end);
        chunks.push(blob)

        start = end;
        end = start + piece;
    }
    return chunks
}


/**
 * 获取url上的字段参数
 * @param { string } name 字段名
 * @param { string } url
 */
export const getUrlParam = (name, url) => {
    if (!url) {
        url = window.location.href
    }
    const reg = new RegExp('[\\[\\]]', 'g')
    name = name.replace(reg, '\\$&')
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
    const results = regex.exec(url)
    if (!results) return ''
    if (!results[2]) return ''
    return decodeURIComponent(results[2].replace(/\+/g, ' '))
}

export const qsFromMap = (map) => {
    let s = ''
    for (const [key, value] of map) {
        s += key + '=' + value + '&'
    }
    s = s.slice(0, -1)

    return s
}

/**
 * @desc 判断是否为FormData
 * @param {*} param
 */
export const isFormData = (param) => {
    return Object.prototype.toString.call(param) === '[object FormData]'
}

/**
 * 截取邮箱类型
 */
export const cutMailType = (mail) => {
    const start = mail.indexOf('@')
    const end = mail.indexOf('.')
    if (start === end) {
        return ''
    }
    return mail.slice(start + 1, end)
}

/**
 * 判断是否是邮箱
 */
export const isMailFormate = (param) => {
    // const testMail = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/
    const testMail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
    return testMail.test(param)
    //   /^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/
}

/**
 * 保留文本换行
 */
export const preText = (pretext) => {
    return pretext
        .replace(/\r\n/g, '<br/>')
        .replace(/\n/g, '<br/>')
        .replace(/\s/g, '&nbsp;')
}

/**
 * 通过文件名获取文件格式
 */
export const getFileExt = (fileName) => {
    const len = fileName.split('.').length
    return len >= 2 ? fileName.split('.')[len - 1].toLowerCase() : 'unknown'
}
/**
 * 获取时间错
 */
export const getExpires = (seconds) => {
    return Math.round(new Date().getTime() / 1000) + seconds
}
/**
 * 判断是否是手机
 */
export const isMobile = () => {
    const flag = navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    )
    return flag
}

export const isAndroidDevice = () => {
    var u = navigator.userAgent;
    if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
        return true
    } else {
        return false
    }
}

/**
 * 是否是iOS移动设备
 * @returns {boolean}
 */
export function isIOSMobile() {
    var ua = navigator.userAgent;
    var  iPad  =  ua.indexOf('iPad')  >  -1;
    var  iPhone  =  ua.indexOf('iPhone')  >  -1 ;
    if  ( iPad  ||  iPhone)  {
        return  true;
    }
    return  false;
}

/**
 * 对象数组去重
 */
export const uniqueArr = function (arr, key) {
    if (arr && arr.length) {
        const newobj = {}
        const newArr = []
        for (var i = 0; i < arr.length; i++) {
            const item = arr[i]
            if (!newobj[item[key]]) {
                newobj[item[key]] = newArr.push(item)
            }
        }
        return newArr
    } else {
        return []
    }
}

/**
 * 判断是否是控对象
 */
export const isNullObject = (object) => {
    if (typeof object !== 'object' || !object) {
        return false
    } else {
        return Object.keys(object).length ? true : false
    }
}



/**
 * 时间格式
 */
export const dateFormat = (date, fmt = 'yyyy-MM-dd hh:mm:ss') => {
    // yyyy/MM/dd hh:mm:ss
    if (!date) return ''
    if (date.constructor !== Date) {
        date = new Date(date)
    }
    const o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
    }
    for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length === 1
                    ? o[k]
                    : ('00' + o[k]).substr(('' + o[k]).length)
            )
        }
    }
    return fmt
}
// 判断星期
export const dateWeek = (date) => {
    date = new Date(date)
    const year = date.getFullYear();
    const month = date.getMonth();
    const day = date.getDate();
    let weekIndex = date.getDay()
    console.warn(weekIndex);
    //   console.warn(year,"年，",month,"月","日",day,"星期",weekIndex);
    return `${$lang.mailMeeting(year, month, day, weekIndex)}`
}

/**
 * 特殊时间格式 邮件列表页
 */

//判断是否前天
function isLastYesterday(time) {
    const twentyFourHours = 24 * 60 * 60 * 1000;
    const fortyEightHours = 24 * 60 * 60 * 1000 * 2;
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const today = `${year}/${month}/${day}`;
    const todayTime = new Date(today).getTime(); // 当天凌晨的时间
    const yesterdayTime = new Date(todayTime - twentyFourHours).getTime(); // 昨天凌晨的时间
    const lastYesterdayTime = new Date(todayTime - fortyEightHours).getTime(); // 昨天凌晨的时间
    return time < yesterdayTime && lastYesterdayTime <= time;
}
//判断是否昨天
function isYesterday(time) {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const today = `${year}/${month}/${day}`;
    const todayTime = new Date(today).getTime(); // 当天凌晨的时间
    const yesterdayTime = new Date(todayTime - 24 * 60 * 60 * 1000).getTime(); // 昨天凌晨的时间
    return time < todayTime && yesterdayTime <= time;
}
export const dateFormatSpecial = (date) => {
    if (!date) return ''
    if (date.constructor !== Date) {
        date = new Date(date)
    }
    let year = date.getFullYear()
    let month = date.getMonth()
    const nowDate = new Date()

    const nowYear = nowDate.getFullYear()
    const nowMonth = nowDate.getMonth()
    const nowDay = nowDate.getDate()
    if (year < nowYear) {
        //往年
        // return `${year}年${date.getMonth() + 1}月${date.getDate()}日`
        return `${$lang.mailYearDate(year, date.getMonth(), date.getDate())}`
    } else if (year == nowYear) {
        //今年
        if (nowMonth == month) {
            // 当月
            if (date.getDate() == nowDay) {
                //今天
                const detailTime = dateFormat(date, 'hh:mm')
                if (0 <= date.getHours() && date.getHours() <= 12) {
                    if (date.getHours() == 12 && date.getMinutes() < 60) {
                        return `${$lang.afternoon} ${detailTime}`
                    }
                    return `${$lang.morning} ${detailTime}`
                } else {
                    return `${$lang.afternoon} ${detailTime}`
                }
            } else {
                //!今天
                if (isYesterday(date)) {
                    return `${$lang.yesterday}`
                } else if (isLastYesterday(date)) {
                    return `${$lang.beforeYesterday}`
                } else {
                    // return `${date.getMonth() + 1}月${date.getDate()}日`
                    return `${$lang.mailMonthDate(date.getMonth(), date.getDate())}`
                }
            }
        } else {
            return `${$lang.mailMonthDate(date.getMonth(), date.getDate())}`
        }
    }
}

// 增加水印 传入标签id 
export const addWatermarkImg = (a) => {
    let container = document.getElementById(`${a}`);
    // console.warn("当前元素",a,container,document.getElementsByTagName(`${a}`));
    let base64Url = localStorage.getItem("watermarkImg");
    container.setAttribute(
        "style",
        `background-repeat:repeat;
      background-image:url('${base64Url}')`
    );
    // const watermarkDiv = document.createElement("div");
    // watermarkDiv.setAttribute(
    //   "style",
    //   `position:absolute;
    //     top:0;
    //     left:0;
    //     width:100%;
    //     height:100%;
    //     pointer-events:none;
    //     background-repeat:repeat;
    //     background-image:url('${base64Url}')`
    // );
    // container[0].style.position = "relative";
    // container[0].insertBefore(watermarkDiv, container.firstChild);
}



/**
 * 是否携带html标签
 */
export const isWithHtml = (str) => {
    const reg = /<[^<>]+>/g
    return reg.test(str)
}



// 监听是否有未读事件改变红点
let changeTabSetTime = null
let count = null
let showTabRed = "";
const getFolderInfo = (folderId) => api.get(`/folder/getFolder`, {
    params: {
        folderId
    }
})
export const checkPoint = (count) => {
    if (count === 0) {
        showTabRed = 0;
    } else {
        showTabRed = -2;
    }
    try {
        console.warn("进入取消红点", showTabRed);
        window.qing.call("setHomeTabBadge", {
            badgeNumber: showTabRed,
            success: (res) => {
                console.warn("红点 桥返回值", res);
            },
        });
    } catch {
        console.error("调用轻setHomeTabBadge失败");
    }
}
export const getUnreadCount = async function () {
    //获取文件夹信息
    // console.warn('getFolderInfo', API.getFolderInfo)
    try {
        const eachRes = await getFolderInfo("inbox");
        // console.error("000");
        const { success, data } = eachRes?.data;
        if (success) {
            count = data.unreadItemCount;
            checkPoint(count)
        }
    } catch {
        console.error(`获取文件夹未读数量失败`);
    }
}

// 修改底部tab红点显示隐藏
export const changeTabRead = () => {
    console.warn("changeTabRead---");
    clearInterval(changeTabSetTime);
    getUnreadCount()
    console.warn("changeTabSetTime", changeTabSetTime);
    changeTabSetTime = setInterval(() => {
        getUnreadCount()
    }, 300000);
}